#!/usr/bin/env groovy

pipeline {

    agent any
    // 全局变量
    environment {
        // 项目名称
        NAME = 'oops-server-analysis'
        // 目标服务器用户名
        SERVER_USERNAME = 'root'
        // 目标服务器地址
        SERVER_ADDRESS = '120.27.19.106'
    }

    stages {
        stage('Checkout') {
            steps {
                echo 'Checking...'
                checkout scm
                echo 'Checkout successful'
            }
        }

        stage('Build') {
            steps {
                echo 'Building'
                sh "mvn clean package"
                echo 'Build successful'
            }
        }

        /**
         * TODO 生成 project.service 有时间在写
         */
        stage('Generator') {
            steps {
                echo 'Generating'
                echo 'TODO'
                echo 'Generator successful'
            }
        }

        stage('Test') {
            steps {
                echo 'Testing'
                echo 'Test successful'
            }

        }

        /**
         * ssh无法登录,提示Pseudo-terminal will not be allocated because stdi
         * 写登陆脚本ssh的时候加个参数
         * ssh -t -t user@10.242.1.1
         * 或者
         * ssh user@10.242.1.1 -tt
         */
        stage('Deploy'){
            steps {
                echo 'Deploying...'
                sh "scp ${NAME}/target/${NAME}-1.0-SNAPSHOT-distribution.tar.gz ${SERVER_USERNAME}@${SERVER_ADDRESS}:~/downloads/"
                sh "ssh ${SERVER_USERNAME}@${SERVER_ADDRESS} -tt 'tar -xf /root/downloads/${NAME}-1.0-SNAPSHOT-distribution.tar.gz -C /soft/'"
                sh "scp ${NAME}/src/main/scripts/${NAME}.service ${SERVER_USERNAME}@${SERVER_ADDRESS}:/etc/systemd/system/"
                sh "ssh ${SERVER_USERNAME}@${SERVER_ADDRESS} -tt 'systemctl daemon-reload'"
                sh "ssh ${SERVER_USERNAME}@${SERVER_ADDRESS} -tt 'systemctl stop ${NAME}.service'"
                sh "ssh ${SERVER_USERNAME}@${SERVER_ADDRESS} -tt 'systemctl enable ${NAME}.service'"
                sh "ssh ${SERVER_USERNAME}@${SERVER_ADDRESS} -tt 'systemctl start ${NAME}.service'"
                echo 'Deploy successful'
            }
        }
    }
}
